<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Download, Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

import VChart from 'vue-echarts'
import type { OperationLog, OperationLogQuery,OperationLogListResponse } from '@/pages/log_operation/components/OperationLog'
import  {logApi} from '@/pages/log_operation/components/OperationLog'
const logs = ref<OperationLog[]>([])

const filters = ref<OperationLogQuery>({
  username: '',
  module: '',
  operationType: '',
  startTime: '',
  endTime: '',
  page: 1,
  size: 10,
})
const timeRange = ref<[string, string]>(['', ''])

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

const chartOptions = ref({})

const fetchLogs = async () => {
  loading.value = true
  const params: OperationLogQuery = {
     ...filters.value,
     startTime: timeRange.value?.[0] || undefined,
     endTime: timeRange.value?.[1] || undefined,
    page: currentPage.value,
    size: pageSize.value,
  }

  try {
    // fetchLogs 里处理
  const res = await logApi.getLogList(params);

    const logRes: OperationLogListResponse = res.data   // 这里解包出真正的数据
    console.log('logRes', logRes)

    logs.value = logRes.records
    total.value = logRes.total

    renderChart(logs.value)
    ElMessage.success('日志获取成功')
  } catch (error) {
    ElMessage.error('日志获取失败')
  } finally {
    loading.value = false
  }
}


// 重置查询条件
const resetFilters = () => {
  filters.value = {
    username: '',
    module: '',
    operationType: '',
    page: 1,
    size: 10,
  }
  timeRange.value = ['', '']
  fetchLogs()
}

const exportExcel = () => {
  const data = logs.value.map(item => [
    item.username,
    item.module,
    item.operationType,
    item.operationContent,
    item.operationResult,
    item.ipAddress,
    item.createdAt
  ])

  const header = [
    '用户名',
    '模块',
    '操作类型',
    '操作内容',
    '结果',
    'IP地址',
    '操作时间'
  ]

  const ws_data = [header, ...data]
  const ws = XLSX.utils.aoa_to_sheet(ws_data)

  // 设置样式
  const range = XLSX.utils.decode_range(ws['!ref']!)
  for (let R = range.s.r; R <= range.e.r; ++R) {
    for (let C = range.s.c; C <= range.e.c; ++C) {
      const cell_address = { c: C, r: R }
      const cell_ref = XLSX.utils.encode_cell(cell_address)
      if (!ws[cell_ref]) continue
      ws[cell_ref].s = {
        font: { name: '微软雅黑', sz: 12, bold: R === 0 },
        alignment: { vertical: 'center', horizontal: 'center' },
        border: {
          top: { style: 'thin', color: { rgb: '000000' } },
          bottom: { style: 'thin', color: { rgb: '000000' } },
          left: { style: 'thin', color: { rgb: '000000' } },
          right: { style: 'thin', color: { rgb: '000000' } }
        },
        fill: R === 0 ? { fgColor: { rgb: 'DCE6F1' } } : undefined
      }
    }
  }

  // 设置列宽
  ws['!cols'] = [
    { wch: 14 }, // 用户名
    { wch: 16 }, // 模块
    { wch: 14 }, // 操作类型
    { wch: 40 }, // 操作内容
    { wch: 10 }, // 结果
    { wch: 16 }, // IP
    { wch: 20 }, // 时间
  ]

  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '操作日志')
  XLSX.writeFile(wb, '操作日志记录.xlsx')
}


// 构建 ECharts 图表
const renderChart = (data: OperationLog[]) => {
  const group: Record<string, number> = {}
  data.forEach(log => {
    group[log.operationType] = (group[log.operationType] || 0) + 1
  })
  chartOptions.value = {
    title: { text: '操作类型统计', left: 'center' },
    tooltip: {},
    xAxis: { type: 'category', data: Object.keys(group) },
    yAxis: { type: 'value' },
    series: [
      {
        name: '数量',
        type: 'bar',
        data: Object.values(group),
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
}

onMounted(fetchLogs)

const onPageSizeChange = (val: number) => {
  pageSize.value = val
  filters.value.size = val
  fetchLogs()
}

const onPageChange = (val: number) => {
  currentPage.value = val
  filters.value.page = val
  fetchLogs()
}
</script>

<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="header">
          <span>操作日志记录</span>
          <el-button type="success" @click="exportExcel" :icon="Download">导出 Excel</el-button>
        </div>
      </template>

      <el-form :model="filters" inline class="filter-bar">
        <el-form-item label="用户名">
          <el-input v-model="filters.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="模块">
          <el-input v-model="filters.module" placeholder="请输入模块名称" clearable />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-input v-model="filters.operationType" placeholder="请输入操作类型" clearable />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 360px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchLogs" :icon="Search">查询</el-button>
          <el-button @click="resetFilters" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="20">
        <el-col :span="18">
          <el-table :data="logs" style="width: 100%" height="500" border stripe v-loading="loading">
            <el-table-column prop="username" label="用户名" width="120" align="center" />
            <el-table-column prop="module" label="模块" width="140" align="center" />
            <el-table-column prop="operationType" label="操作类型" width="120" align="center" />
            <el-table-column prop="operationContent" label="操作内容" min-width="200" />
            <el-table-column prop="operationResult" label="结果" width="100" align="center" />
            <el-table-column prop="ipAddress" label="IP地址" width="140" align="center" />
            <el-table-column prop="createdAt" label="操作时间" width="180" align="center" />
          </el-table>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
            class="pagination-container"
            @size-change="onPageSizeChange"
            @current-change="onPageChange"
          />
        </el-col>
        <el-col :span="6">
          <el-card class="chart-container">
            <v-chart :option="chartOptions" style="height: 500px;" autoresize />
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 0 10px;
}

.el-form-item {
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 0 10px;
}

.chart-container {
  height: 100%;
  padding: 10px;
  box-shadow: none;
}

.chart-container :deep(.el-card__body) {
  padding: 0;
  height: 100%;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  overflow-x: hidden;
}

:deep(.el-table--scrollable-y) {
  height: 400px !important;
}
</style>
